const imgElements: HTMLCollectionOf<HTMLElement> = document.getElementsByClassName("box-img") as HTMLCollectionOf<HTMLElement>;
let currentIndex: number = 0;
let intervalId: number | undefined;

const listItems: NodeListOf<Element> = document.querySelectorAll('.radis ul li');

// 为每个 li 添加点击事件监听器
listItems.forEach((item: Element, index: number) => {
    item.addEventListener('click', () => {
        showImage(index);
        startAutoSwitch(); // 重置定时器
    });
});

function showImage(index: number): void {
    // 将所有图片的透明度设置为0
    for (let i = 0; i < imgElements.length; i++) {
        imgElements[i].style.opacity = '0';
        (listItems[i] as HTMLElement).style.backgroundColor = '#fff';
    }

    // 显示指定索引的图片
    imgElements[index].style.opacity = '1';
    (listItems[index] as HTMLElement).style.backgroundColor = '#a69898';
}

// 自动切换图片
function startAutoSwitch(): void {
    clearInterval(intervalId); // 取消当前定时器
    intervalId = setInterval(() => {
        currentIndex = (currentIndex + 1) % imgElements.length;
        showImage(currentIndex);
    }, 3000); // 重新启动新的定时器
}

// 初始化自动切换
startAutoSwitch();

// 实现 add 函数
function add(): void {
    currentIndex = (currentIndex + 1) % imgElements.length;
    showImage(currentIndex);
    startAutoSwitch(); // 重置定时器
}

// 实现 subtraction 函数
function subtraction(): void {
    currentIndex = (currentIndex - 1 + imgElements.length) % imgElements.length;
    showImage(currentIndex);
    startAutoSwitch(); // 重置定时器
}